import {designPage, reactive, useRefs} from "plain-design-composition";
import {$message, Adc, AdcAddress, AdcAddressItem, AdcIndex, AdcInput, AdcInputNumber, AdcTextarea, AntdTable, Button, ButtonGroup, Form, FormItem, iAdtNode, iAdtRowRenderScope, Segment, SegmentGroup} from "../../../../packages";
import {DemoRow} from "../../Demo/DemoRow";
import data50 from '../../../data/data-50.json';
import {deepcopy} from "plain-utils/object/deepcopy";

export const demo1 = designPage(() => {

  const { refs, onRef } = useRefs({
    AntdTable: AntdTable
  });

  const state = reactive({
    data: data50.slice(0, 5),
    editNodes: [] as iAdtNode[],

    onDblClickRow({ node }: iAdtRowRenderScope) {
      if (!node.state.edit) {
        node.enableEdit();
        state.editNodes.push(node);
      }
    },
    saveEdit: async () => {
      const validates = (await Promise.all(state.editNodes.map(node => node.validate()))).filter(Boolean);
      if (validates.length > 0) {
        console.log(validates);
        const { validateResultData, node: { state: { index } } } = validates[0]!;
        $message.error(`第${index + 1}条记录校验不通过，${validateResultData[0].label}:${validateResultData[0].message}`);
        return;
      }
      // todo 网络保存逻辑
      state.editNodes.forEach(AntdTableNode => AntdTableNode.saveEdit(AntdTableNode.state.editRow));
      state.editNodes.forEach(AntdTableNode => AntdTableNode.closeEdit());
      state.editNodes = [];
    },
    cancelEdit: () => {
      state.editNodes.forEach(AntdTableNode => {
        AntdTableNode.cancelEdit();
      });
      state.editNodes = [];
    },
  });

  return () => (
    <DemoRow title={'基本用法'}>
      <Form column={1}>
        <FormItem label="导出">
          <ButtonGroup style={{ margin: '4px 0' }}>
            <Button label="导出原始数据" onClick={() => console.log(refs.AntdTable!.methods.getSourceData())}/>
            <Button label="导出显示数据" onClick={() => refs.AntdTable!.methods.getShowData().then(val => console.log(val))}/>
          </ButtonGroup>
        </FormItem>
        <FormItem label={'编辑'}>
          <ButtonGroup disabled={state.editNodes.length === 0}>
            <Button onClick={state.saveEdit} label={'保存编辑'}/>
            <Button onClick={state.cancelEdit} label={'取消编辑'}/>
          </ButtonGroup>
        </FormItem>
      </Form>
      <AntdTable
        dataSource={state.data}
        onRowDoubleClick={state.onDblClickRow}
        ref={onRef.AntdTable}
      >
        <AdcIndex/>
        <Adc dataIndex="id" title="编号"/>
        <AdcInput dataIndex="name" title="文本框" required/>
        <AdcAddressItem dataIndex="province" title="省" province/>
        <AdcAddressItem dataIndex="city" title="市" city parentField="province"/>
        <AdcAddressItem dataIndex="district" title="县" district parentField="city"/>
        <AdcInputNumber dataIndex="num" title="数字"/>
      </AntdTable>
    </DemoRow>
  );
});

export const demo2 = designPage(() => {

  const { refs, onRef } = useRefs({
    AntdTable: AntdTable
  });

  const state = reactive({
    data: data50.slice(0, 5) as any[],
    editNodes: [] as iAdtNode[],
    formEdit: false,

    onDblClickRow({ node }: iAdtRowRenderScope) {
      if (state.formEdit) {
        refs.AntdTable!.formEditor.methods.edit({
          node: node,
          onConfirm: (node) => {
            state.data[node.state.index] = deepcopy(node.state.editRow);
          }
        });
      } else {
        if (!node.state.edit) {
          node.enableEdit();
          state.editNodes.push(node);
        }
      }
    },
    saveEdit: async () => {
      const validates = (await Promise.all(state.editNodes.map(node => node.validate()))).filter(Boolean);
      if (validates.length > 0) {
        console.log(validates);
        const { validateResultData, node: { state: { index } } } = validates[0]!;
        $message.error(`第${index + 1}条记录校验不通过，${validateResultData[0].label}:${validateResultData[0].message}`);
        return;
      }
      // todo 网络保存逻辑
      state.editNodes.forEach(AntdTableNode => AntdTableNode.saveEdit(AntdTableNode.state.editRow));
      state.editNodes.forEach(AntdTableNode => AntdTableNode.closeEdit());
      state.editNodes = [];
    },
    cancelEdit: () => {
      state.editNodes.forEach(AntdTableNode => {
        AntdTableNode.cancelEdit();
      });
      state.editNodes = [];
    },
  });

  return () => (
    <DemoRow title={'合并列'}>
      <Form column={1}>
        <FormItem label="大小尺寸">
          <SegmentGroup v-model={state.formEdit}>
            <Segment label="行内编辑" val={false}/>
            <Segment label="表单编辑" val={true}/>
          </SegmentGroup>
        </FormItem>
        <FormItem label="导出">
          <ButtonGroup style={{ margin: '4px 0' }}>
            <Button label="导出原始数据" onClick={() => console.log(refs.AntdTable!.methods.getSourceData())}/>
            <Button label="导出显示数据" onClick={() => refs.AntdTable!.methods.getShowData().then(val => console.log(val))}/>
          </ButtonGroup>
        </FormItem>
        <FormItem label={'编辑'}>
          <ButtonGroup disabled={state.editNodes.length === 0}>
            <Button onClick={state.saveEdit} label={'保存编辑'}/>
            <Button onClick={state.cancelEdit} label={'取消编辑'}/>
          </ButtonGroup>
        </FormItem>
      </Form>
      <AntdTable
        dataSource={state.data}
        onRowDoubleClick={state.onDblClickRow}
        ref={onRef.AntdTable}
      >
        <AdcIndex/>
        <Adc dataIndex="id" title="编号"/>
        <AdcInput dataIndex="name" title="文本框" required/>
        <AdcAddress/>
        <AdcInputNumber dataIndex="num" title="数字"/>
        <AdcTextarea dataIndex="name" title="长文本"/>
      </AntdTable>
    </DemoRow>
  );
});
